package com.jiangdg.demo

import android.annotation.SuppressLint
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toolbar
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gyf.immersionbar.ImmersionBar
import java.io.File

class FolderActivity : AppCompatActivity() {

    private var immersionBar: ImmersionBar? = null
    private lateinit var folderAdapter: FolderAdapter
    private val folderList: MutableList<File> = mutableListOf()

    private lateinit var toggleMode: TextView
    private lateinit var tvCheck: TextView
    private lateinit var ivCheck: ImageView
    private lateinit var llCheck: LinearLayout
    private lateinit var tvDelete: TextView
    private val folderRenameReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.action?.let {
                if (it == FolderRenameBroadcast.ACTION_FOLDER_RENAMED) {
                    refreshFolderData()
                }
            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBar()
        setContentView(R.layout.activity_folder)

        setupRecyclerView()

        // 注册广播接收器
        val filter = IntentFilter(FolderRenameBroadcast.ACTION_FOLDER_RENAMED)
        registerReceiver(folderRenameReceiver, filter)

        val usersFolder = File(filesDir, "users")
        var folders = usersFolder.listFiles { file -> file.isDirectory } ?: emptyArray()
        folders = folders.sortedByDescending { it.lastModified() }.toTypedArray()
        folderAdapter.setData(folders.toMutableList())

        findViewById<ImageView>(R.id.ivBack).setOnClickListener { finish() }

        tvDelete = findViewById(R.id.tvDelete)
        tvDelete.setOnClickListener {
            //删除所有选择的
            folderAdapter.deleteSelectedItems()
            toggleBottomCheck()
        }
        llCheck = findViewById(R.id.llCheck)
        ivCheck = findViewById(R.id.ivCheck)
        tvCheck = findViewById(R.id.tvCheck)
        ivCheck.setOnClickListener {
            if (tvCheck.text == getString(R.string.text_0014)){
                folderAdapter.selectedAllItems()
            }else{
                folderAdapter.clearSelection()
            }
            toggleBottomCheck()
        }

        toggleMode = findViewById(R.id.tvEditModel)
        toggleMode.setOnClickListener {
            folderAdapter.toggle()
            toggleMode.text = if (folderAdapter.editMode) getString(R.string.text_0016) else getString(R.string.text_0013)
            toggleBottomCheck()
        }
    }

    private fun toggleBottomCheck() {
        if (!folderAdapter.editMode){
            llCheck.visibility = View.GONE
        }else{
            llCheck.visibility = View.VISIBLE
        }
        val count = folderAdapter.getSelectedItemCount()
        if (count == 0) {
            ivCheck.setImageResource(R.drawable.icon_round_un_select)
            tvCheck.text = getString(R.string.text_0014)
            return
        }
        if (count == folderAdapter.itemCount) {
            ivCheck.setImageResource(R.drawable.icon_round_select)
            tvCheck.text = getString(R.string.text_0017)
            return
        }
        if (count < folderAdapter.itemCount) {
            ivCheck.setImageResource(R.drawable.icon_half_round_un_select)
            tvCheck.text = getString(R.string.text_0014)
        }
    }

    private fun setupRecyclerView() {
        val recyclerView = findViewById<RecyclerView>(R.id.folder_recycler_view)
        folderAdapter =
            FolderAdapter(this, mutableListOf(), object : ThumbnailAdapter.OnItemSelectListener {
                override fun onSelect(file: File) {
                    val resultIntent = Intent()
                    resultIntent.putExtra("result", file.name)
                    setResult(Activity.RESULT_OK, resultIntent)
                    finish()
                }

                override fun onCheckChange(file: File) {
                    toggleBottomCheck()
                }
            })
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = folderAdapter

        // 加载数据
//        refreshFolderData()
    }

    private fun refreshFolderData() {
        val usersFolder = File(filesDir, "users")
        var folders = usersFolder.listFiles { file -> file.isDirectory } ?: emptyArray()
        folders = folders.sortedByDescending { it.lastModified() }.toTypedArray()

        // 重新加载文件夹数据
        folderList.clear()
        folderAdapter.setData(folders.toMutableList())
    }

    override fun onResume() {
        super.onResume()
        refreshFolderData()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(folderRenameReceiver)

        immersionBar = null
    }

    private fun setStatusBar() {
        immersionBar = ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .statusBarColor(R.color.white)
            .navigationBarColor(R.color.white)
            .fitsSystemWindows(true)
            .keyboardEnable(true)
        immersionBar?.init()
    }
}
